package com.jingdianjichi.auth.domain.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.google.gson.Gson;
import com.jingdianjichi.auth.common.enums.AuthUserStausEnum;
import com.jingdianjichi.auth.common.enums.IsDeletedEnum;
import com.jingdianjichi.auth.domain.constants.AuthConstant;
import com.jingdianjichi.auth.domain.convert.AuthUserConverter;
import com.jingdianjichi.auth.domain.entity.AuthUserBO;
import com.jingdianjichi.auth.domain.redis.RedisUtil;
import com.jingdianjichi.auth.domain.service.AuthUserDomainService;
import com.jingdianjichi.auth.infra.basic.entity.*;
import com.jingdianjichi.auth.infra.basic.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AuthUserDomainServiceImpl implements AuthUserDomainService {

    @Resource
    AuthUserService authUserService;

    @Resource
    AuthUserRoleService authUserRoleService;

    @Resource
    AuthPermissionService authPermissionService;

    @Resource
    AuthRolePermissionService authRolePermissionService;

    private String authPermissonPrefix = "auth.permisson";

    private String authRolePrefix = "auth.role";

    private static final String LOGIN_PREFIX="loginCode";
    @Resource
    RedisUtil redisUtil;

    @Resource
    AuthRoleService authRoleService;

    String salt = "123456";
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean register(AuthUserBO authUserBO) {
        AuthUser authUserExist = new AuthUser();
        authUserExist.setUserName(authUserBO.getUserName());
        List<AuthUser> authUserList=authUserService.queryAllByLimit(authUserExist);
        if(authUserList.size()>0){
            return true;
        }
        AuthUser authUser = AuthUserConverter.INSTANCE.converterBoToAuthUser(authUserBO);
        if(StringUtils.isNotBlank(authUser.getPassword())){
            authUser.setPassword(SaSecureUtil.md5BySalt(salt, authUserBO.getPassword()));
        }
        authUser.setIsDeleted(IsDeletedEnum.UN_DELETED.getCode());
        authUser.setStatus(AuthUserStausEnum.OPEN.getCode());
        //insert用户
        Integer insert = authUserService.insert(authUser);
        AuthRole authRole=new AuthRole();
        authRole.setRoleKey(AuthConstant.NORMAL_USER);
        AuthRole authRole1 = authRoleService.queryByCondition(authRole);
        Long role1Idid = authRole1.getId();
        Long userId = authUser.getId();
        AuthUserRole authUserRole=new AuthUserRole();
        authUserRole.setRoleId(role1Idid);
        authUserRole.setUserId(userId);
        authUserRole.setIsDeleted(IsDeletedEnum.UN_DELETED.getCode());
        //插入权限角色表
        authUserRoleService.insert(authUserRole);

        List<AuthRole> roleList=new ArrayList<>();
        roleList.add(authRole);
        String roleKey = redisUtil.buildKey(authRolePrefix, authUser.getUserName());
        redisUtil.set(roleKey,new Gson().toJson(roleList));

        AuthRolePermission authRolePermission=new AuthRolePermission();
        authRolePermission.setRoleId(authRole1.getId());
        authRolePermission.setIsDeleted(IsDeletedEnum.UN_DELETED.getCode());
        List<AuthRolePermission> authRolePermissionList=authRolePermissionService.queryByCondition(authRolePermission);
        List<Long> permissionIdList=new ArrayList<>();
        for(AuthRolePermission authRolePermission1:authRolePermissionList){
            permissionIdList.add(authRolePermission1.getPermissionId());
        }

        List<AuthPermission> authPermissionList1 = authPermissionService.queryByPermissionList(permissionIdList);
        String permissionKey = redisUtil.buildKey(authPermissonPrefix, authUser.getUserName());
        redisUtil.set(permissionKey,new Gson().toJson(authPermissionList1));
        return insert>0;
    }

    @Override
    public Boolean update(AuthUserBO authUserBO) {
        AuthUser authUser = AuthUserConverter.INSTANCE.converterBoToAuthUser(authUserBO);
        Integer update = authUserService.update(authUser);
        return update > 0 ;
    }

    @Override
    public Boolean delete(AuthUserBO authUserBO) {
        AuthUser authUser = AuthUserConverter.INSTANCE.converterBoToAuthUser(authUserBO);
        authUser.setIsDeleted(IsDeletedEnum.DELETED.getCode());
        Integer update = authUserService.update(authUser);
        return update>0;
    }

    @Override
    public SaTokenInfo doLogin(String vaildCode) {
        String loginKey = redisUtil.buildKey(LOGIN_PREFIX, vaildCode);
        String openId = redisUtil.get(loginKey);
        if(StringUtils.isBlank(openId)){
            return null;
        }
        AuthUserBO authUserBO=new AuthUserBO();
        authUserBO.setUserName(openId);
        this.register(authUserBO);
        StpUtil.login(openId);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return tokenInfo;
    }

    @Override
    public AuthUserBO getUserInfo(AuthUserBO authUserBO) {
        AuthUser authUserExist = new AuthUser();
        authUserExist.setUserName(authUserBO.getUserName());
        List<AuthUser> authUserList=authUserService.queryAllByLimit(authUserExist);
        if(CollectionUtils.isEmpty(authUserList)){
            return new AuthUserBO();
        }
        AuthUser authUser=authUserList.get(0);
        return AuthUserConverter.INSTANCE.authUserToAuthUserBo(authUser);
    }
}
